package cn.zwx.zookeeper.config.example.utils;

import cn.zwx.zookeeper.config.example.config.ymal.ApplicationRootConfiguration;
import cn.zwx.zookeeper.config.example.config.ymal.Config;
import cn.zwx.zookeeper.config.example.config.ymal.SpringConfig;
import cn.zwx.zookeeper.config.example.config.ymal.ZookeeperConfig;
import org.yaml.snakeyaml.Yaml;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author zhangwenxue
 */
public class YamlLoader {

    /**
     * 解析yaml工具类
     */
    public static  <T> T load (File file,Class<T> clazz){
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            Yaml yaml = new Yaml();
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            return yaml.loadAs(bufferedInputStream, clazz);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (Objects.nonNull(bufferedInputStream)){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (Objects.nonNull(fileInputStream)){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 解析loadForZookeeperConfig
     */
    public static ZookeeperConfig loadForZookeeperConfig (File file,Class<ApplicationRootConfiguration> clazz){
      ApplicationRootConfiguration applicationRootConfiguration = load(file, clazz);
      if (Objects.isNull(applicationRootConfiguration)){
          throw new RuntimeException("applicationRootConfiguration 配置加载失败！");
        }
      SpringConfig configurationSpring = applicationRootConfiguration.getSpring();
      if (Objects.isNull(configurationSpring)){
          throw new RuntimeException("未配置spring相关属性！");
      }
      Config springConfig = configurationSpring.getConfig();
      if (Objects.isNull(springConfig)){
          throw new RuntimeException("未配置spring config相关属性！");
      }
      ZookeeperConfig zookeeper = springConfig.getZookeeper();
      if (Objects.isNull(zookeeper)){
          throw new RuntimeException("未配置spring config zookeeper相关属性！");
      }
      return zookeeper;
    }
}
